package com.lm.nacosconfig.controller;

import com.alibaba.nacos.api.annotation.NacosInjected;
import com.alibaba.nacos.api.config.ConfigService;
import com.alibaba.nacos.api.config.ConfigType;
import com.alibaba.nacos.api.config.annotation.NacosConfigListener;
import com.lm.nacosconfig.component.DynamicThreadPoolManager;
import org.apache.commons.lang3.SystemUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import static com.alibaba.nacos.api.common.Constants.DEFAULT_GROUP;
import static org.springframework.web.bind.annotation.RequestMethod.GET;

@RestController
public class ThreadPoolController {

    @NacosInjected
    private ConfigService configService;
    @Autowired
    private DynamicThreadPoolManager threadPoolManager;

    @GetMapping("/submit-task")
    public String submitTask() {
        threadPoolManager.getExecutor().execute(() -> {
            System.out.println("执行任务，线程名：" + Thread.currentThread().getName());
        });
        return "任务已提交";
    }

    /**
     * 修改nacos中心配置
     * @throws Exception
     */
    @RequestMapping(value = "/publishConfig", method = GET)
    @ResponseBody
    public void publishConfig() throws Exception {
        StringBuilder builder = new StringBuilder();
        builder.append("threadpool.corePoolSize = 1");
        builder.append(SystemUtils.LINE_SEPARATOR);
        builder.append("threadpool.maximumPoolSize = 14");
        builder.append(SystemUtils.LINE_SEPARATOR);
        builder.append("threadpool.queueCapacity =200");
        // 通过注入服务 configService 的publishConfig修改配置
        // publishConfig存在会修改，不存在添加
        configService.publishConfig("dynamic-threadpool.yaml", DEFAULT_GROUP,
                builder.toString());
    }

    /**
     * 通过注解配置监听器
     * 配置转换为字符串类型
     * @param value
     */
    @NacosConfigListener(dataId = "dynamic-threadpool.yaml",  type = ConfigType.YAML)
    public void onReceived(String value) {
        System.out.println(11211);
//        logger.info("onReceived(String) : {}", value);
    }



}
